import { history, RequestConfig, useDispatch } from 'umi';
import userApi from './api/user';
import { UserInfoResult } from './api/user';
import { post } from './utils/request';
import { clearJump } from './utils/navigator';
import { clearCookie, isLogin } from './utils/common';

/**
 * 修改clientRender 参数
 * @param memo
 * @returns
 */
export function modifyClientRenderOpts(memo: any) {
  return {
    ...memo,
  };
}

/**
 * 修改路由
 * @param param0
 */
export function patchRoutes({ routes }: { routes: any }) {}

/**
 * 覆写 render
 * @param oldRender
 */
export function render(oldRender: Function) {
  oldRender();
}

/**
 * 在初始加载和路由切换时做一些事情。
 * 比如用于做埋点统计
 * @param param0
 */
export function onRouteChange({
  location,
  routes,
  action,
}: {
  location: any;
  routes: any;
  action: any;
}) {
  if (
    location.pathname == '/login' ||
    location.pathname == '/forgetpwd' ||
    location.pathname == '/register'
  ) {
    // 如果已经登录了
    if (isLogin()) {
      clearJump('/');
    }
  }
}

/**
 * 获取初始数据
 */
export async function getInitialState() {
  const data = await post<UserInfoResult>(userApi.userInfo);
  return data;
}

/**
 * 请求处理
 */
export const request: RequestConfig = {
  timeout: 1000,
  middlewares: [],
  requestInterceptors: [],
  responseInterceptors: [],
  prefix: '/api',
  errorHandler: function (err) {
    const { statusCode, status } = err.data || {};
    const dispatch = useDispatch();
    // 当接口返回未登录时跳转到登录页面
    switch (statusCode) {
      case 403:
        clearCookie('wavevpn');
        dispatch({
          type: 'security/save',
          payload: {
            needLogin: true,
          },
        });
        break;
    }
  },
};
